﻿using System;

public class Solution994
{
    public int OrangesRotting(int[][] grid)
    {

        int m = grid.Length;
        int n = grid[0].Length;
        int[][] time = new int[m][];
        for (int i = 0; i < m; i++)
        {

            time[i] = new int[n];
        }
        Queue<int> stack = new Queue<int>();

        for (int i = 0; i < m; i++)
        {


            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 2)
                {
                    stack.Enqueue(i);
                    stack.Enqueue(j);

                    time[i][j] = 0;

                }

            }
        }



        while (stack.Count > 0)
        {

           
            int i = stack.Dequeue();
            int j = stack.Dequeue();




            Console.WriteLine("row:  "+i+ "   col:  " + j);
          


            //上
            if (i - 1 >= 0)
            {
                if (grid[i - 1][j] == 1)
                {//只有新鲜的变2.。0和2都不变
                    grid[i - 1][j] = 2;
                    time[i - 1][j] = time[i ][j] + 1;
                    stack.Enqueue(i - 1);
                    stack.Enqueue(j);

                }

            }

            //下
            if (i + 1 < m && grid[i + 1][j] == 1)
            {

                grid[i + 1][j] = 2;
                time[i + 1][j] = time[i][j] + 1;
                stack.Enqueue(i + 1);
                stack.Enqueue(j);

            }
            //左
            if (j - 1 >= 0 && grid[i][j - 1] == 1)
            {

                grid[i][j - 1] = 2;
                time[i][j - 1] = time[i][j ] + 1;
                stack.Enqueue(i);
                stack.Enqueue(j - 1);
            }

           
            //右
            if (j + 1 < n && grid[i][j + 1] == 1)
            {

                grid[i][j + 1] = 2;
                time[i][j + 1] = time[i][j ] + 1;
                stack.Enqueue(i);
                stack.Enqueue(j + 1);
            }

            Console.WriteLine(time[i][j]);





        }

        int restime = 0;
        for (int i = 0; i < m; i++)
        {


            for (int j = 0; j < n; j++)
            {

                if (grid[i][j] == 1)//不可达的地方
                {
                    return -1;
                }
                

                restime = Math.Max(time[i][j], restime);
                

                   
            }
        }

        return restime;

    }
}

class Program994
{


    static void Main994(string[] args)
    {
        int[][] grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]];
        Solution994 solution = new Solution994();
      int res=  solution.OrangesRotting(grid);
        Console.WriteLine(res);

    }
}